package site.timers.chat.util.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.Data;

import java.util.Scanner;

/**
 * @Classname GroupChatClient
 * @Description TODO
 * @Version 1.0.0
 * @Date 2025/8/12 14:48
 * @Author twl
 */
@Data
public class GroupChatClient {

    private String host;

    private int port;

    public GroupChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group).channel(NioSocketChannel.class)
                    .handler(new GroupChatClientChannelInitializer());
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            //输入信息
            Channel channel = channelFuture.channel();
            System.out.println("--------" + channel.localAddress() + "----------");

            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                String msg = scanner.nextLine();
                channel.writeAndFlush(msg + "\n");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new GroupChatClient("127.0.0.1", 7000).run();
    }
}
